package com.atguigu.admin.controller;

import com.atguigu.admin.bean.City;
import com.atguigu.admin.bean.User;
import com.atguigu.admin.service.CityService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;

/**
 * @author anan
 * @create 2021-08-25 10:42
 */
@Slf4j
@Controller
public class IndexController {
    @GetMapping(value = {"/", "/login"} )
    public String loginPage(){
        return "login";
    }

    @Autowired
    CityService cityService;

    @ResponseBody
    @GetMapping("/city")
    public City getCityById(@RequestParam("id") long id){
        return cityService.getById(id);
    }

    @ResponseBody
    @PostMapping("/city")
    public City saveCity(City city){
        cityService.saveCity(city);
        log.info(city.toString());
        return city;
    }


    @PostMapping("/login")
    public String main(User user, HttpSession session, Model model){
        if (StringUtils.hasLength(user.getUserName()) && StringUtils.hasLength(user.getPassword())){
            session.setAttribute("user", user);
            return "redirect:/main.html";
        }
        else{
            model.addAttribute("msg","账号密码错误");
            return "login";
        }
    }

    @GetMapping("/main.html")
    public String mainPage(HttpSession session, Model model){
/*        Object user = session.getAttribute("user");
        if (user != null){
            return "main";
        }
        else {
            model.addAttribute("msg","请重新登录");
            return "login";
        }*/
        return "main";
    }
}
